Ext.define('App.hdfs.view.DirectoryTree', {
    extend: "Extend.tree.Panel",
    alias: 'widget.DirectoryTree',
    requires: ['App.hdfs.model.FsNode', 'Extend.grid.column.CdtColumn'],
    displayField: 'name',
    rootVisible: true,
    hideHeaders: false,
    forceFit: true,
    rowLines: true,
    columnLines: true,
    config: {},
    store: {
        autoLoad: false,
        model: 'App.hdfs.model.FsNode',
        nodeParam: "path",
        root: {
            name: '加载...',
            iconCls: 'Folder',
            expanded: false,
            file: false,
            path: '/',
            name: '根目录'
        },
        proxy: {
            type: 'ajax',
            url: 'hdfs/get_children',
            idParam: 'path',
            reader: {
                type: 'json',
                rootProperty: 'data',
                totalProperty: 'total'
            }
        }
    },
    columns: [{
        xtype: 'treecolumn',
        text: '',
        dataIndex: 'name'
    }, {
        text: '大小(byte)',
        dataIndex: 'size'
    }, {
        text: '创建人',
        dataIndex: 'owner'
    }, {
        xtype: 'CdtColumn',
        text: '最后修改时间',
        dataIndex: 'modificationTime'
    }],
    listeners: {
        afterrender: function () {
            var me = this;
            if (!Ext.isEmpty(me.getRootNode())) {
                me.getRootNode().set('path', '/')
                me.getRootNode().set('name', "加载...")
                me.reloadNode(me.getRootNode());
            }
        },
        load: function ($this, records, successful, operation, node, eOpts) {
            var me = this;
            if (node.isRoot()) {
                node.set('name', "根目录");
            }
            Ext.Array.each(records, function (record) {
                if (record.get('leaf') == true) {
                    record.set('iconCls', 'File')
                    record.set('leaf', true);
                } else {
                    record.set('iconCls', 'Folder')
                }
            })
        },
        itemdblclick: function ($this, record, item, index, e, eOpts) {
            var me = this;
            if (record.get('leaf') === false) {
                if (record.isExpanded() == true) {
                    record.collapse(true);
                    record.set('loaded', false)
                } else {
                    record.expand(false);
                }
            } else if (record.get('leaf') === true) {
                var size = record.get('size');
                if (size > 5 * 1024 * 1024) {
                    Extend.MessageBox.confirm('提示', '由于文件太大，无法直接打开编辑，是否下载该文件？', null, function (opt) {
                        if (opt == 'yes') {
                            me.downloadHandler(record.get('path'));
                        }
                    })
                } else {
                    me.editHandler.call(me, record)
                }
            }
        },
        cellcontextmenu: function ($this, td, cellIndex, record, tr, rowIndex, e, eOpts) {
            var me = this;
            if (cellIndex == 0) {
                var items = [{
                    text: '刷新',
                    iconCls: 'refresh',
                    disabled: record.get('leaf') == true,
                    handler: function () {
                        me.mask('刷新...');
                        me.reloadNode(record);
                    }
                }, {
                    text: '修改',
                    iconCls: 'delete',
                    disabled: record.isRoot() == true,
                    handler: function () {
                        if (!Ext.isEmpty(record)) {
                            if (record.get('leaf') === true) {
                                me.editHandler.call(me, record);
                            } else if (record.get('leaf') == false) {
                                me.renameHandler.call(me, record)
                            }
                        }
                    }
                }, {
                    text: '删除',
                    iconCls: 'delete',
                    disabled: record.isRoot() == true,
                    handler: function () {
                        if (!Ext.isEmpty(record)) {
                            me.deleteHandler.call(me, record);
                        }
                    }
                },];
                if (record.get('leaf') == true) {
                    items.push({
                        text: '下载文件',
                        iconCls: 'Download',
                        handler: function () {
                            var path = record.get('path')
                            me.downloadHandler(path)
                        }
                    });
                } else {
                    items = items.concat([{
                        text: '创建目录',
                        iconCls: 'AddTaskBean',
                        handler: function () {
                            if (!Ext.isEmpty(record)) {
                                me.createDirectoryHandler.call(me, record);
                            }
                        }
                    }, {
                        text: '上传文件',
                        iconCls: 'Upload',
                        handler: function () {
                            var path = record.get('path')
                            me.uploadHandler(path)
                        }
                    }]);
                }
                var menu = Ext.create('Ext.menu.Menu', {items: items});
                e.preventDefault();
                e.stopEvent();// 这两个很重要，否则点击鼠标右键还是会出现浏览器的选项
                menu.showAt(e.getXY())
            }
        }
    },
    downloadHandler: function (path) {
        var me = this;
        window.open('hdfs/download?path=' + path)
    },
    renameHandler: function (target) {
        var me = this;
        Ext.Msg.prompt('重命名', '请输入新的名称名称：', function (opt, val) {
            if (opt == "ok") {
                me.mask('修改...');
                Ext.Ajax.request({
                    url: 'hdfs/rename',
                    success: function (resp) {
                        if (resp.result.data == true) {
                            me.reloadNode(target.parentNode);
                        }
                    },
                    params: {
                        path: target.get('path'),
                        name: val
                    },
                    callback: function () {
                        me.unmask();
                    }
                });
            }
        });
    },
    editHandler: function (record) {
        var me = this;
        if (record.isRoot()) {
            return;
        }
        if (record.get('leaf') == true) {
            me.mask('加载...');
            var path = record.get('path')
            Ext.Ajax.request({
                url: 'hdfs/read?path=' + path,
                success: function (resp) {
                    if (resp.result.success == true) {
                        var content = resp.result.data;
                        Ext.create('App.hdfs.view.HdfsFileEditor', {
                            title: path,
                            url: 'hdfs/save_file'
                        }).show().loadRecord(Ext.create('Ext.data.Model', {
                            path: path,
                            content: content
                        }))
                    }
                },
                method: 'GET',
                callback: function () {
                    me.unmask();
                }
            });
        }
    },
    createDirectoryHandler: function (target) {
        var me = this;
        Ext.Msg.prompt('创建目录', '请输入目录名称：', function (opt, val) {
            if (opt == "ok") {
                me.mask('创建...');
                Ext.Ajax.request({
                    url: 'hdfs/create_directory',
                    success: function (resp) {
                        if (resp.result.data == true) {
                            me.reloadNode(target);
                        }
                    },
                    params: {
                        path: target.get('path'),
                        name: val
                    },
                    callback: function () {
                        me.unmask();
                    }
                });
            }
        });
    },
    deleteHandler: function (target) {
        var me = this;
        me.mask('删除...');
        Ext.Ajax.request({
            url: 'hdfs/delete',
            success: function (resp) {
                if (resp.result.data == true) {
                    target.parentNode.removeChild(target);
                }
            },
            params: {
                path: target.get('path')
            },
            callback: function () {
                me.unmask();
            }
        });
    },
    uploadHandler: function (target) {
        var me = this;
        var win = Ext.create('Extend.window.ImportWindow', {title: '上传', url: 'hdfs/upload', message: "请选择需要上传的文件，最大500M。"});
        win.formPanel.add({xtype: 'hidden', name: 'path', value: target});
        win.show();
    },
    reloadNode: function (record) {
        var me = this;

        var opts = {
            success: function (record, operation) {
                if (record.get('leaf') != true) {
                    record.set('loaded', false)
                    record.set('expanded', false)
                    record.expand();
                }
            }
        };
        record.load(opts);
    },
    deselectAll: function () {
    },
    reload: function () {
    }
})